<template>
  <div class="searchBar">
    <input
      class="searchBar-input"
      v-model="searchKey"
      placeholder="请输入关键词查询，如：0000001 或 上证指数"
      @keyup.enter="searchStock"
    />
    <div class="suggestList" v-show="showSuggestList">
      <div
        class="suggestList-item"
        v-for="item in suggestList"
        :key="item.label"
        @click="addStock(item)"
      >
        {{item.label}}
        {{item.description}}
      </div>
    </div>
  </div>
</template>

<script>
import {reactive, toRefs} from 'vue';
import {sendMessageToBackgroundPopupScript} from '../../assets/js/utils';
export default {
  name: 'searchBar',
  setup(props, context) {
    const data = reactive({
      searchKey: '',
      suggestList: '',
      showSuggestList: false
    })
    const searchStock = () => {
      if (data.searchKey) {
        sendMessageToBackgroundPopupScript({
          greeting: 'searchKey',
          data: { searchKey: data.searchKey }
        }, res => {
          data.suggestList = res
          data.showSuggestList = true
        })
      }
    }
    // 添加股票
    const addStock = (stockMsg) => {
      let code = ''
      if (stockMsg.description === '美股') {
        code = 'usr_' + stockMsg.label.split(' | ')[0].substring(2)
      } else {
        code = stockMsg.label.split(' | ')[0]
      }
      context.emit('addStock', code)
    }
    const hide = () => {
      data.showSuggestList = false
      data.searchKey = ''
    }
    return {
      ...toRefs(data),
      searchStock,
      addStock,
      hide
    }
  }
}
</script>

<style scoped lang="less">
.searchBar {
  position: fixed;
  top: -60px;
  left: 50%;
  width: 500px;
  transform: translate(-50%,0);
  transition: all 0.3s;
  z-index: 9999999;
}
.searchBar-input {
  width: 500px;
  height: 36px;
  line-height: 36px;
  border: 1px solid #cccccc;
  border-radius: 5px;
  outline-color: #409EFF;
  padding: 0 5px;
}
.suggestList {
  border: 1px solid rgb(204,204,204);
  border-radius: 0 0 5px 5px;
  border-top: none;
  background: #ffffff;
}
.suggestList-item {
  padding:0px 10px;
  cursor: pointer;
  line-height: 2em;
  color: gray;
}
</style>
